import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/live/expert_rooms_logic.dart';
import 'package:sports_new/entity/live/expert_room_entity.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../resources/colours.dart';
import '../../utils/routes.dart';
import '../../utils/utils.dart';
import '../../widgets/card.dart';
import '../../widgets/base/qkd_text.dart';

class ExpertRoomsPage extends StatefulWidget {
  const ExpertRoomsPage({super.key});

  @override
  State<ExpertRoomsPage> createState() => _ExpertRoomsPageState();
}

class _ExpertRoomsPageState extends State<ExpertRoomsPage> {
  final ExpertRoomsLogic logic = Get.put(ExpertRoomsLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ExpertRoomsLogic>(
      builder: (logic) {
        return VisibilityDetector(
          key: const Key("rooms"),
          onVisibilityChanged: (VisibilityInfo info) {
            if(!info.visibleBounds.isEmpty) {
              logic.getRefresh();
            }
          },
          child: Scaffold(
            backgroundColor: Colours.greyF2F3F7,
            appBar: Styles.appBar(
              title: const Text("我的直播间"),
              actions: [
                GestureDetector(
                  onTap: () => Get.toNamed(Routes.liveCreate),
                  child: Image.asset(
                    Utils.getImgPath("add_circle.png"),
                    width: 24,height: 24
                  ).paddingOnly(right: 16),
                )
              ]
            ),
            body: EasyRefresh(
              controller: logic.refreshController,
              onRefresh: logic.getRefresh,
              onLoad: logic.loadMore,
              footer: Styles.refreshFooter(position: IndicatorPosition.locator),
              child: LoadingWidget<bool>(
                isLoading: logic.rooms == null,
                data: logic.rooms?.length == 0,
                needScroll: true,
                child: () => CustomScrollView(
                  slivers: [
                    if(logic.scheduleRoom.hasValue)...[
                      SliverToBoxAdapter(
                        child: const QkdText(
                          "待直播",
                          fontSize: 16, fontWeight: FontWeight.w500
                        ).paddingOnly(top: 12,left: 12,right: 12),
                      ),
                      SliverList.builder(
                        itemCount: logic.scheduleRoom?.length,
                        itemBuilder: (context,index)=> room(
                          logic.scheduleRoom![index]
                        )
                      )
                    ],
                    if(logic.checkRoom.hasValue)...[
                      SliverToBoxAdapter(
                        child: const QkdText(
                          "审核中",
                          fontSize: 16, fontWeight: FontWeight.w500
                        ).paddingOnly(top: 12,left: 12,right: 12),
                      ),
                      SliverList.builder(
                        itemCount: logic.checkRoom?.length,
                        itemBuilder: (context,index)=> room(
                          logic.checkRoom![index]
                        )
                      )
                    ],
                    if(logic.pastRoom.hasValue)...[
                      SliverToBoxAdapter(
                        child: const QkdText(
                          "已结束",
                          fontSize: 16, fontWeight: FontWeight.w500
                        ).paddingOnly(top: 12,left: 12,right: 12),
                      ),
                      SliverList.builder(
                        itemCount: logic.pastRoom?.length,
                        itemBuilder: (context,index)=> room(
                          logic.pastRoom![index]
                        )
                      )
                    ],
                    const FooterLocator.sliver()
                  ],
                )
              ),
            ),
          ),
        );
      }
    );
  }

  Widget room(ExpertRoomEntity entity){
    String liveStatus = "未开始";
    Color tagColor = Colours.blue149CFF;
    if(entity.status == 1){
      liveStatus = "直播中";
      tagColor = Colours.main;
    }else{
      if(entity.publishTime.hasValue){
        var time = DateTime.parse(entity.publishTime!);
        String hour = time.formatedString('HH:mm');
        if(time.isInToday()){
          liveStatus = "今天 $hour";
        }else {
          liveStatus = "${time.month}月${time.day}日 $hour";
        }
      }
      if(entity.status == 2) {
        tagColor = Colours.grey99;
      }
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Block(
          cardStyle: const CardStyle(
            margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
            padding: EdgeInsets.all(10)
          ),
          child: SizedBox(
            height: 70,
            child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Stack(
                    alignment: AlignmentDirectional.topEnd,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: CachedNetworkImage(
                          height: 70,
                          width: 125,
                          fit: BoxFit.cover,
                          imageUrl: entity.image ?? ""
                        ),
                      ),
                      Container(
                        height: 14,
                        alignment: Alignment.center,
                        padding: const EdgeInsets.symmetric(horizontal: 4),
                        decoration: BoxDecoration(
                          color: tagColor,
                          borderRadius: BorderRadius.circular(3)
                        ),
                        child: QkdText(
                          liveStatus,
                          height: 1.4,
                          color: Colours.white,fontSize: 10
                        ),
                      )
                    ],
                  ),
                  Container(width: 10),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        QkdText(
                          entity.title ?? "",
                          maxLines: entity.homeName.hasValue && entity.awayName.hasValue?1:2,
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                        if(entity.homeName.hasValue && entity.awayName.hasValue)...[
                          Container(height: 2),
                          QkdText(
                            "${entity.homeName} vs ${entity.awayName}",
                            color: Colours.grey99,
                            fontSize: 12,
                            maxLines: 1
                          )
                        ],
                        const Spacer(),
                        Row(
                          children: [
                            if(entity.status != 0)
                              DefaultTextStyle(
                                style: const TextStyle(fontSize: 12,color: Colours.grey99),
                                child: Row(
                                    children: [
                                      Image.asset(Utils.getImgPath("live_hot.png"),width: 12,height: 12),
                                      Container(width: 2),
                                      QkdText("${entity.hot ?? " "}",needCenter: true)
                                    ]
                                ),
                              ),
                            const Spacer(),
                            if(entity.status != 2)...[
                              if(entity.id != null && entity.pushUrl.hasValue)
                                QkdButton(
                                    width: 76,height: 24,
                                    onPressed: () => logic.toLive(entity),
                                    borderRadius: 12,
                                    text: "开始直播",
                                    backgroundColor: Colours.main,
                                    foregroundColor: Colours.white,
                                    strutStyle: Styles.centerStyle(fontSize: 13),
                                    textStyle: const TextStyle(fontSize: 13)
                                )
                            ]
                            else
                              GestureDetector(
                                onTap: () => Get.toNamed(Routes.liveStatistics,arguments: entity.id),
                                child: Row(
                                  children: [
                                    const QkdText("查看数据",fontSize: 12,color: Colours.grey66,needCenter: true),
                                    Image.asset(
                                      Utils.getImgPath('arrow_right_36.png'),
                                      width: 12
                                    )
                                  ],
                                ),
                              )
                          ],
                        )
                      ],
                    ),
                  )
                ]
            ),
          ),
        ),
      ],
    );
  }
}
